import io
import base64
from PIL import Image, ImageDraw, ImageFont
from PIL import ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True


#####  图片压缩代码
def img_compress(logo, width=80, height=80):
    logo = logo.split(";base64,")[-1]  # 删除前面的图片属性
    logo_img = base64.b64decode(logo)  # base64解码
    img_type = "png"  # 后面需要转换的类型, 不涉及gif, 就固定为 png
    img_input = io.BytesIO(logo_img)  # img转为 二进制
    img_input_size = len(img_input.getvalue()) // 1024
    pil_input = Image.open(img_input)
    x, y = pil_input.size
    if x > y:
        # print("横屏")
        k = width / x
    else:
        # print("竖屏")
        k = height / y
    pil_out = pil_input.resize((int(x * k), int(y * k)), Image.ANTIALIAS)
    img_out = io.BytesIO()
    pil_out.save(img_out, img_type)
    img_compress = base64.b64encode(img_out.getvalue())
    base64_str = str(img_compress, 'utf-8')
    src = 'data:{0};base64,{1}'.format(img_type, base64_str)
    return src


if __name__ == '__main__':
    text = ""
    res = img_compress(text)
    print(res)
